package com.jp.knowledge.adapter;


import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.anarchy.classify.simple.SimpleAdapter;
import com.jp.knowledge.R;
import com.jp.knowledge.dialog.ExperienceMergedDialog;
import com.jp.knowledge.model.experience.TiyanApps;
import com.jp.knowledge.util.ImageLoadUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/1/19.
 */

public class ExperienceAdapter extends SimpleAdapter<TiyanApps, ExperienceAdapter.ItemViewHolder> implements View.OnClickListener {

    private static int MAX_ICON_TITLE_LENGTH = 5;

    private Context context;
    private boolean isEdit;
    private ExperienceMergedDialog mergedDialog;

    public ExperienceAdapter(List<List<TiyanApps>> data, Context context) {
        super(data);
        this.context = context;
        this.isEdit = false;
        initDialog();
    }

    /* 设置编辑状态 */
    public void setEdit(boolean isEdit){
        this.isEdit = isEdit;
        getMainAdapter().notifyDataSetChanged();
        getSubAdapter().notifyDataSetChanged();
    }

    public List<List<TiyanApps>> getData(){
        return mData;
    }

    private void initDialog(){
        mergedDialog = new ExperienceMergedDialog(context);
        mergedDialog.setLeftListener(this);
        mergedDialog.setRightListener(this);
    }

    @Override
    public View getView(ViewGroup parent, View convertView, int mainPosition, int subPosition) {
//        if(convertView == null)
//            convertView = LayoutInflater.from(context).inflate(R.layout.experience_icon, parent, false);
//        ImageView iconImageView = (ImageView) convertView.findViewById(R.id.experience_icon);
//        String url = mData.get(mainPosition).get(subPosition).getIcon();
//        if("add".equals(mData.get(mainPosition).get(subPosition).getPid()))
//            iconImageView.setImageResource(R.mipmap.add_to);
//        else if(url != null)
//            ImageLoadUtil.loadrund(parent.getContext(), url, iconImageView, 10);
//        else
//            iconImageView.setImageResource(R.mipmap.morentutouxiang);
//        return convertView;

        // TODO 此处需优化，没有对 view 进行复用（复用会造成应为文件夹内图标和外部图标大小不一致导致外部图标大小出现错乱）
        View iconView = LayoutInflater.from(context).inflate(R.layout.experience_icon, parent, false);
        ImageView iconImageView = (ImageView)iconView.findViewById(R.id.experience_icon);
        String url = mData.get(mainPosition).get(subPosition).getIcon();
        if(url != null)
            ImageLoadUtil.loadrund(parent.getContext(), url, iconImageView, 10);
        else if("add".equals(mData.get(mainPosition).get(subPosition).getPid()))
            iconImageView.setImageResource(R.mipmap.add_to);
        return iconView;
    }

    @Override
    protected ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context)
                .inflate(R.layout.experience_item, parent, false);
        return new ItemViewHolder(itemView);
    }

    @Override
    protected void onBindMainViewHolder(ItemViewHolder holder, int position) {
        if(mData.get(position).size() > 1) {
            holder.experienceFlag.setVisibility(View.GONE);
            String groupName = mData.get(position).get(0).getGName();
            if(groupName.length() > MAX_ICON_TITLE_LENGTH)
                groupName = groupName.substring(0, MAX_ICON_TITLE_LENGTH);
            holder.iconName.setText(groupName);
        } else {
            if(mData.get(position).get(0).getIsExp() == 1)
                holder.experienceFlag.setVisibility(View.VISIBLE);
            else
                holder.experienceFlag.setVisibility(View.GONE);
            String iconName = mData.get(position).get(0).getPName();
            if(iconName.length() > MAX_ICON_TITLE_LENGTH)
                iconName = iconName.substring(0, MAX_ICON_TITLE_LENGTH);
            holder.iconName.setText(iconName);
        }
        if(isEdit){
            if(mData.get(position).size() > 1){
                holder.editCheck.setVisibility(View.INVISIBLE);
                int groupCheckNum = 0;
                for(TiyanApps data : mData.get(position)){
                    if(data.getIsCheck())
                        groupCheckNum++;
                }
                if(groupCheckNum == 0){
                    holder.checkNum.setVisibility(View.GONE);
                } else{
                    holder.checkNum.setVisibility(View.VISIBLE);
                    holder.checkNum.setText(groupCheckNum+"");
                }
            } else{
                holder.editCheck.setVisibility(View.VISIBLE);
                holder.editCheck.setChecked(mData.get(position).get(0).getIsCheck());
                holder.checkNum.setVisibility(View.GONE);
            }
        } else{
            holder.editCheck.setVisibility(View.GONE);
            holder.checkNum.setVisibility(View.GONE);
        }
        setIconViewBackground(isEdit, holder.contentView);
    }

    @Override
    protected void onBindSubViewHolder(ItemViewHolder holder, int mainPosition, int subPosition) {
        if(mData.get(mainPosition).get(subPosition).getIsExp() == 1)
            holder.experienceFlag.setVisibility(View.VISIBLE);
        else
            holder.experienceFlag.setVisibility(View.GONE);
        String iconName = mData.get(mainPosition).get(subPosition).getPName();
        if(iconName != null && iconName.length() > MAX_ICON_TITLE_LENGTH)
            iconName = iconName.substring(0, MAX_ICON_TITLE_LENGTH);
        holder.iconName.setText(iconName==null ? "" : iconName);
        if(isEdit){
            holder.editCheck.setVisibility(View.VISIBLE);
            holder.editCheck.setChecked(mData.get(mainPosition).get(subPosition).getIsCheck());
            holder.checkNum.setVisibility(View.GONE);
        } else{
            holder.editCheck.setVisibility(View.GONE);
            holder.checkNum.setVisibility(View.GONE);
        }
        setIconViewBackground(isEdit, holder.contentView);
    }

    private void setIconViewBackground(boolean isEdit, View iconView){
        if(isEdit)
            iconView.setBackgroundResource(R.color.translate);
        else
            iconView.setBackgroundResource(R.drawable.normal_click_bg);
    }

    @Override
    protected void onItemClick(ItemViewHolder itemViewHolder, int parentIndex, int index) {
        if(isEdit && itemViewHolder.editCheck.getVisibility() == View.VISIBLE){
            itemViewHolder.editCheck.setChecked(!itemViewHolder.editCheck.isChecked());
            TiyanApps data = mData.get(parentIndex).get(index<0 ? 0 : index);
            data.setIsCheck(!data.getIsCheck());
            if(index >= 0) {
                notifyItemChanged(parentIndex);
                if (this.allItemCheckListener != null) {
                    for (TiyanApps apps : mData.get(parentIndex)) {
                        if (!apps.getIsCheck()) {
                            this.allItemCheckListener.onAllItemCheck(false);
                            return;
                        }
                    }
                    this.allItemCheckListener.onAllItemCheck(true);
                }
            }
        } else if(!isEdit && iconClickListener != null) {
            if(index < 0 && mData.get(parentIndex).size() > 1)
                return;
            iconClickListener.onIconClick(parentIndex, index<0 ? 0 : index);
        }
    }

    @Override
    protected void onDragStart(ItemViewHolder itemViewHolder, int parentIndex, int index) {
        if(!isEdit && mData.get(parentIndex).size() > 1 && index >= 0){
            List<TiyanApps> groupData = mData.get(parentIndex);
            TiyanApps lastApp = groupData.get(groupData.size()-1);
            if(lastApp.getPid().equals("add"))
                groupData.remove(lastApp);
        }
        if(!isEdit && switchToEditListener != null){
            switchToEditListener.switchToEdit();
        }
    }

    @Override
    protected void onMerged(int selectedPosition, int targetPosition) {
        super.onMerged(selectedPosition, targetPosition);
        int groupPosition = selectedPosition<targetPosition ? targetPosition-1 : targetPosition;
        if (mData.get(groupPosition).size() <= 2) {
            mergedDialog.setSelectedPosition(selectedPosition);
            mergedDialog.setTargetPosition(targetPosition);
            mergedDialog.show();
        } else{
            List<TiyanApps> group = mData.get(groupPosition);
            group.get(group.size()-1).setGName(group.get(0).getGName());
            group.get(group.size()-1).setGid(group.get(0).getGid());
            group.get(group.size()-1).setParentMid(group.get(0).getParentMid());
            /* 图标入组回调 */
            if(this.actionHappenedListener != null){
                List<String> mergedIconId = new ArrayList<>();
                mergedIconId.add(group.get(group.size()-1).getMid());
                this.actionHappenedListener.iconsMoveIn(mergedIconId, group.get(0).getGid());
            }
        }
    }

    @Override
    protected int onLeaveSubRegion(int parentPosition, List<TiyanApps> tiyanAppses, int selectedPosition) {
        /* 图标出组回调 */
        if(this.actionHappenedListener != null) {
            List<String> leaveIcon = new ArrayList<>();
            leaveIcon.add(tiyanAppses.get(selectedPosition).getMid());
            this.actionHappenedListener.iconsMoveOut(leaveIcon, tiyanAppses.get(0).getGid());
        }
        return super.onLeaveSubRegion(parentPosition, tiyanAppses, selectedPosition);
    }

    @Override
    protected boolean canDragOnLongPress(int mainPosition, int subPosition) {
        if(subPosition > 0 && "add".equals(mData.get(mainPosition).get(subPosition).getPid()))
            return false;
        return super.canDragOnLongPress(mainPosition, subPosition);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_btn:     // 取消合并组
                int selectedPosition = mergedDialog.getSelectedPosition();
                int targetPosition = mergedDialog.getTargetPosition();
                TiyanApps data;
                if(selectedPosition < targetPosition){
                    data = mData.get(targetPosition-1).remove(mData.get(targetPosition-1).size()-1);
                } else{
                    data = mData.get(targetPosition).remove(mData.get(targetPosition).size()-1);
                }
                List<TiyanApps> list = new ArrayList<>();
                list.add(data);
                mData.add(selectedPosition, list);
                if(selectedPosition < targetPosition) {
                    notifyItemChanged(targetPosition-1);
                } else{
                    notifyItemChanged(targetPosition);
                }
                notifyItemInsert(selectedPosition);
                break;
            case R.id.right_btn:        // 合并组
                int groupPosition = mergedDialog.getTargetPosition();
                if(mergedDialog.getSelectedPosition() < groupPosition)
                    groupPosition -= 1;
                for(TiyanApps tiyanApps : mData.get(groupPosition))
                    tiyanApps.setGName(mergedDialog.getEditText());     // // TODO: 2017/2/6 新建组组id未确定
                notifyItemChanged(groupPosition);
                mergedDialog.dismiss();
                /* 组创建回调 */
                if(this.actionHappenedListener != null){
                    this.actionHappenedListener.groupCreated(mData.get(groupPosition));
                }
                break;
        }
    }

    @Override
    protected void onSubDialogShow(Dialog dialog, int parentPosition) {
        if(this.subDialogShowListener != null)
            this.subDialogShowListener.onSubDialogShow(dialog, parentPosition);
    }
    /* 次级对话框展开监听器 */
    SubDialogShowListener subDialogShowListener;
    public void setSubDialogShowListener(SubDialogShowListener subDialogShowListener){
        this.subDialogShowListener = subDialogShowListener;
    }
    public interface SubDialogShowListener{
        void onSubDialogShow(Dialog dialog, int parentPosition);
    }
    /* 次级对话框全选监听器 */
    private AllItemCheckListener allItemCheckListener;
    public void setAllItemCheckListener(AllItemCheckListener allItemCheckListener){
        this.allItemCheckListener = allItemCheckListener;
    }
    public interface AllItemCheckListener{
        void onAllItemCheck(boolean isAllItemCheck);
    }
    /* 长按切换到编辑状态监听器 */
    private SwitchToEditListener switchToEditListener;
    public void setSwitchToEditListener(SwitchToEditListener switchToEditListener){
        this.switchToEditListener = switchToEditListener;
    }
    public interface SwitchToEditListener{
        void switchToEdit();
    }
    /* 图标单击监听器 */
    private IconClickListener iconClickListener;
    public void setIconClickListener(IconClickListener iconClickListener){
        this.iconClickListener = iconClickListener;
    }
    public interface IconClickListener{
        void onIconClick(int parentIndex, int index);
    }
    /* 事件监听器 */
    private ActionHappenedListener actionHappenedListener;
    public void setActionHappenedListener(ActionHappenedListener actionHappenedListener){
        this.actionHappenedListener = actionHappenedListener;
    }
    public interface ActionHappenedListener{
        void groupCreated(List<TiyanApps> groupData);           // 组创建回调
        void iconsMoveIn(List<String> iconsId, String groupId); // 图标进组回调
        void iconsMoveOut(List<String> iconsId, String groupId);// 图标出组回调
    }

    protected static class ItemViewHolder extends SimpleAdapter.ViewHolder{
        View contentView;
        ImageView experienceFlag;
        TextView iconName;
        CheckBox editCheck;
        TextView checkNum;
        public ItemViewHolder(View iconView){
            super(iconView);
            contentView = iconView;
            this.experienceFlag = (ImageView) contentView.findViewById(R.id.experience_flag);
            this.iconName = (TextView) contentView.findViewById(R.id.experience_icon_name);
            this.editCheck = (CheckBox) contentView.findViewById(R.id.experience_icon_edit_check);
            this.checkNum = (TextView) contentView.findViewById(R.id.experience_icon_check_num);
        }
    }
}
